package validator

import (
	"errors"
	"regexp"
	"strings"
)

var (
	ErrValidEmail   = errors.New("invalid email format")
	ErrEmailTooLong = errors.New("email too long")

	emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
)

type EmailValidator interface {
	Validate(email string) error
}

type SimpleEmailValidator struct {
	maxLen int
}

func NewEmailValidator(maxLen int) *SimpleEmailValidator {
	if maxLen <= 0 {
		maxLen = 254
	}

	return &SimpleEmailValidator{maxLen: maxLen}
}

func (s *SimpleEmailValidator) Validate(email string) error {
	email = strings.TrimSpace(email)

	if len(email) == 0 {
		return ErrValidEmail
	}

	if len(email) > s.maxLen {
		return ErrEmailTooLong
	}

	if !emailRegex.MatchString(email) {
		return ErrValidEmail
	}

	return nil
}

func IsValidEmail(email string) (bool, error) {
	validator := NewEmailValidator(254)
	err := validator.Validate(email)
	return err == nil, err
}
